//
//  XMUserDetailVoiceView.m
//  XunMi
//
//  Created by MacBook on 2024/2/22.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMUserDetailVoiceView.h"
#import "XMAudioPlayer.h"
@interface XMUserDetailVoiceView () <XMAudioPlayerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *anImgView;
@property (weak, nonatomic) IBOutlet UILabel *timeLa;
@property (weak, nonatomic) IBOutlet UIView *anBgV;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *anW;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *anH;

@end


@implementation XMUserDetailVoiceView

- (void)awakeFromNib {
    [super awakeFromNib];
    NSMutableArray *imgs = @[].mutableCopy;
    for (int i = 1; i < 7; i++) {
        [imgs addObject:kGetImage(kStringFormat(@"user_d_voice%d", i))];
    }
    self.anImgView.animationImages = imgs;
    self.anImgView.animationDuration = 1.0;
}

- (void)setModel:(XMUserModel *)model {
    _model = model;
    self.timeLa.text = kStringFormat(@"%ld″",model.voice_intro.voice_length);
}

- (IBAction)playAction:(UIButton *)sender {
    if (![XMUtil isBlankString:self.model.voice_intro.file_url]) {
        if (self.startBlock) {
            self.startBlock();
        }
        self.anW.constant = 23;
        self.anH.constant = 23;
        self.isPlaying = YES;
        [self.anImgView startAnimating];
        if (![XMAudioPlayer.sharedInstance isPlaying]) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSData *data =
                [[NSData alloc] initWithContentsOfURL:kStringToUrl(self.model.voice_intro.file_url)];
                [XMAudioPlayer sharedInstance].delegate = self;
                [[XMAudioPlayer sharedInstance] startPlayVoiceData:data time:0];
                
            });
        }
    }
}

- (void)playerDidFinishPlaying:(AVAudioPlayer *)player flag:(BOOL)flag {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self stopPlay];
        if (self.endBlock) {
            self.endBlock();
        }
    });
}

- (void)stopPlay {
    if ([XMAudioPlayer.sharedInstance isPlaying]) {
        [[XMAudioPlayer sharedInstance] stopPlay];
    }
    [self.anImgView stopAnimating];
    self.isPlaying = NO;
    self.anW.constant = 7;
    self.anH.constant = 9;
    self.anImgView.image = kGetImage(@"user_d_voice_p");
}

- (void)layoutSubviews {
    [super layoutSubviews];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
                                                   byRoundingCorners:(UIRectCornerTopRight | UIRectCornerBottomRight)
                                                         cornerRadii:CGSizeMake(15.5, 15.5)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
    kCornerRadius(_anBgV, _anBgV.bounds.size.width / 2, 0, UIColor.clearColor);
}

@end
